﻿namespace ADIGRE.Infrastructure.NHibernateMaps.Conventions
{
    #region Using Directives

    using FluentNHibernate.Conventions;
    using FluentNHibernate.Conventions.Instances;
    using FluentNHibernate.Conventions.Inspections;
    using System.Diagnostics;

    #endregion

    public class ManyToManyConvention : IHasManyToManyConvention
    {
        #region IConvention<IManyToManyCollectionInspector,IManyToManyCollectionInstance> Members

        //public void Apply(FluentNHibernate.Conventions.Instances.IManyToManyCollectionInstance instance)
        //{
        //    if (instance.OtherSide == null)
        //        instance.Table(string.Format("{0}To{1}", instance.EntityType.Name, instance.ChildType.Name));
        //    else
        //        instance.Inverse();
        //    instance.Cascade.All();
        //}

        public void Apply(IManyToManyCollectionInstance instance)
        {
            Debug.Assert(instance.OtherSide != null);
            // Hack:  the cast is nessesary because the compiler tries to take the Method and not the property
            if (((IManyToManyCollectionInspector)instance.OtherSide).Inverse)
            {
                instance.Table(
                   string.Format(
                       "{0}To{1}",
                       instance.EntityType.Name + "_Id",
                       instance.ChildType.Name + "_Id"));
            }
            else
            {
                instance.Inverse();
            }
            instance.Cascade.All();
        }

        #endregion
    }
}